<template>
  <div class="upload-container">
    <el-tabs v-model="activeTab" type="card" class="custom-tabs">
      <!-- 文件上传Tab -->
      <el-tab-pane label="文件上传" name="upload">
        <div class="upload-section">
          <el-upload class="upload-wrapper" ref="upload" drag action="" multiple="false" :limit="1" :auto-upload="true"
            accept=".zip" :show-file-list="true" :http-request="handleUpLoad" :on-success="handleSuccess"
            :on-error="handleError" :on-remove="handleRemove" :on-exceed="handleExceed" :on-preview="handlePreview"
            :on-change="handleChange" :on-progress="handleProgress" :file-list="fileList" :before-upload="beforeUpload"
            :element-loading-text="uploadStatusText" :element-loading-spinner="uploading ? 'el-icon-loading' : ''">
            <div class="upload-area">
              <el-icon class="upload-icon" :class="{ 'uploading': uploading }">
                <upload-filled />
              </el-icon>
              <div class="upload-text">
                <p class="main-text" v-if="!uploading">拖拽文件到此处或<em>点击上传</em></p>
                <p class="main-text" v-if="uploading"><em>上传中...</em></p>
                <p class="sub-text">支持单个ZIP文件，最大300MB</p>
              </div>


              <!-- <transition name="el-fade-in">
                <div v-if="uploadProgress > 0" class="progress-bar">
                  <el-progress 
                    :percentage="uploadProgress" 
                    :stroke-width="4"
                    :show-text="false"
                    :color="uploadProgressColor"
                  />
                </div>
              </transition> -->
            </div>

            <!-- 添加进度条显示区域 -->
            <template #file="{ file }">
              <div class="upload-progress-container">

                <div class="file-progress">
                  <div class="file-name" v-if="file.status === 'ready' || file.status === 'uploading'">{{ file.name }}
                  </div>
                  <div class="file-name" v-if="file.status === 'success' || file.status === 'exception'"
                    @click="handleDownloadFile(handleFileName(filePaths[0].resultFilePath), baseUrl)">{{ file.name }}
                  </div>
                  <el-progress class="file-progress-status" v-if="file.status === 'uploading'"
                    :percentage="file.percentage" :stroke-width="2"
                    :status="file.status === 'exception' ? 'exception' : ''" />
                </div>

                <div class="file-icon">
                  <el-icon v-if="file.status === 'ready' || file.status === 'uploading'" color="#409EFF">
                    <Loading />
                  </el-icon>
                  <el-icon v-if="file.status === 'success'" color="#67C23A">
                    <CircleCheck />
                  </el-icon>
                  <el-icon v-if="file.status === 'exception'" color="#F56C6C">
                    <CircleCheck />
                  </el-icon>
                  <el-icon v-if="file.status === 'success' || file.status === 'exception'" color="#F56C6C"
                    @click.stop="handleRemove(file)">
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </template>

            <!-- <template #tip>
              <div class="upload-tips">
                <el-alert 
                  v-if="fileList.length > 0"
                  :title="`已上传: ${fileList[0].name}`"
                  type="success"
                  :closable="false"
                  show-icon
                />
                <el-alert 
                  v-else
                  title="请上传ZIP格式的压缩文件"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>
            </template> -->
          </el-upload>
        </div>
      </el-tab-pane>

      <!-- 字符串处理Tab -->
      <el-tab-pane label="RAS加密" name="string">
        <div class="string-section">
          <div class="string-header">
            <h3>RAS加密</h3>
            <el-button type="primary" size="small" @click="handleSubmitResString" :disabled="!reqString.trim()"
              :loading="stringProcessing">
              加密
            </el-button>
          </div>

          <div class="string-input">
            <el-input v-model="reqString" placeholder="请输入要处理的字符串..." clearable type="textarea" :rows="8"
              resize="none" />
          </div>

          <div class="string-output">
            <div class="output-header">
              <span>处理结果</span>
              <el-tooltip content="复制到剪贴板" placement="top">
                <el-button type="text" :icon="CopyDocument" @click="handleCopy" :disabled="!resString" />
              </el-tooltip>
            </div>
            <el-input v-model="resString" type="textarea" :rows="8" readonly resize="none" class="output-content"
              placeholder="处理结果将显示在这里..." />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage, ElNotification } from "element-plus";
import { UploadFilled, CopyDocument } from '@element-plus/icons-vue';
import { postUploadResFile, getResString } from "@/api/project/index";
import type { UploadInstance, UploadProps, UploadRawFile, UploadFile } from 'element-plus';
import { genFileId } from 'element-plus';
import { handleDownloadFile, handleFileName } from "@/utils/utils";
import request from '@/utils/request';

const baseUrl = ref("");
const activeTab = ref('upload'); // 默认激活上传Tab
const fileList = ref<UploadFile[]>([]);
const filePaths = ref<any[]>([]);
const upload = ref<UploadInstance>();
const uploading = ref(false);
const uploadProgress = ref(0);
const stringProcessing = ref(false);
const reqString = ref("");
const resString = ref("");

// 计算属性
const uploadStatusText = computed(() => {
  return uploadProgress.value < 100
    ? `上传中 ${uploadProgress.value}%`
    : '处理中...';
});

const uploadProgressColor = computed(() => {
  if (uploadProgress.value < 30) return '#f56c6c';
  if (uploadProgress.value < 70) return '#e6a23c';
  return '#67c23a';
});

// 上传前验证 - 修改为300MB限制
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isZip = file.type === 'application/zip' || file.name.endsWith('.zip');
  const isLt300M = file.size / 1024 / 1024 < 300; // 300MB限制

  if (!isZip) {
    ElMessage.error('只能上传ZIP格式的文件!');
    return false;
  }
  if (!isLt300M) {
    ElMessage.error('文件大小不能超过300MB!');
    return false;
  }

  // 显示上传进度
  uploadProgress.value = 0;
  const interval = setInterval(() => {
    if (uploadProgress.value < 90) {
      uploadProgress.value += 10;
    } else {
      clearInterval(interval);
    }
  }, 300);

  return true;
};

// 自定义上传
const handleUpLoad = async (options: any) => {
  uploading.value = true;
  console.log("options:", options);
  try {
    // const res = await postUploadResFile(options.file);
    const { file } = options;
    const formData = new FormData();
    formData.append('file', file);

    const res = await request.post('/file/uploadResFile', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {

        console.log("progressEvent:", progressEvent);
        if (progressEvent.total) {
          options.onProgress({
            percent: Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            )
          })
        }
      }
    })
    uploadProgress.value = 100;
    options.onSuccess(res);
  } catch (error: any) {
    uploadProgress.value = 0;
    options.onError(error);
    uploading.value = false;
    ElNotification.error({
      title: '上传失败',
      message: error.message || '文件上传失败，请重试',
    });
  }
};

const handleSuccess = (response: any) => {
  filePaths.value = [response.data.data];
  uploading.value = false;
  ElNotification.success({
    title: '上传成功',
    message: '文件已成功上传并处理',
  });
};

const handleError = (error: any) => {
  uploading.value = false;
  uploadProgress.value = 0;
  ElNotification.error({
    title: '上传错误',
    message: error.message || '上传过程中发生错误',
  });
};

const handleRemove = (v: any) => {
  fileList.value = [];
  filePaths.value = [];
  uploadProgress.value = 0;
};

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  // upload.value!.handleStart(file);
  // ElMessage.warning('已替换之前选择的文件');
};

const handlePreview = () => {
  if (filePaths.value.length > 0) {
    handleDownloadFile(handleFileName(filePaths.value[0].resultFilePath), '');
  }
};

const handleChange = (file: UploadFile) => {
  fileList.value = [file];
};

const handleProgress = (event: any, uploadFile: any) => {
  // Element Plus 会自动更新 file.percentage
};

// 字符串处理
const handleSubmitResString = async () => {
  if (!reqString.value.trim()) {
    ElMessage.warning('请输入要处理的字符串');
    return;
  }

  stringProcessing.value = true;
  try {
    const { data } = await getResString(reqString.value);
    if (data.code === 200) {
      resString.value = data.msg;
      ElMessage.success('处理成功');
    } else {
      throw new Error(data.msg);
    }
  } catch (error: any) {
    ElMessage.error(error.message || '处理失败');
  } finally {
    stringProcessing.value = false;
  }
};

// 复制功能
const handleCopy = async () => {
  if (!resString.value) {
    ElMessage.warning('没有可复制的内容');
    return;
  }

  try {
    await navigator.clipboard.writeText(resString.value);
    ElMessage.success('已复制到剪贴板');
  } catch (err) {
    // 降级方案
    const textarea = document.createElement('textarea');
    textarea.value = resString.value;
    textarea.style.position = 'fixed';
    document.body.appendChild(textarea);
    textarea.select();

    try {
      document.execCommand('copy');
      ElMessage.success('已复制到剪贴板');
    } catch (err) {
      console.error('复制失败:', err);
      ElMessage.error('复制失败，请手动复制');
    } finally {
      document.body.removeChild(textarea);
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-container {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;

  .custom-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }

    :deep(.el-tabs__item) {
      padding: 0 24px;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
    }
  }

  .upload-section {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 24px;

    .upload-wrapper {
      :deep(.el-upload) {
        width: 100%;
      }

      :deep(.el-upload-dragger) {
        width: 100%;
        padding: 40px 20px;
        border: 2px dashed var(--el-border-color);
        transition: all 0.3s;

        &:hover {
          border-color: var(--el-color-primary);
        }
      }
    }

    .upload-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;

      .upload-icon {
        font-size: 48px;
        color: var(--el-color-primary-light-5);
        margin-bottom: 16px;
        transition: all 0.3s;

        &.uploading {
          animation: rotate 2s linear infinite;
        }
      }

      .upload-text {
        text-align: center;

        .main-text {
          font-size: 16px;
          color: var(--el-text-color-regular);
          margin-bottom: 8px;

          em {
            color: var(--el-color-primary);
            font-style: normal;
            font-weight: 500;
          }
        }

        .sub-text {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }

      .progress-bar {
        position: absolute;
        bottom: -10px;
        left: 0;
        right: 0;
        width: 100%;
      }
    }

    .upload-tips {
      margin-top: 16px;
    }

  }

  // 文件列表样式
  .upload-progress-container {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;

    .file-progress {
      width: calc(100% - 40px);
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;

      // .file-name {
      //   width: calc(100% - 40px);
      // }
      .file-progress-status {
        width: calc(100% - 60px);
        font-size: 10px;
      }

    }

    .file-icon {
      width: 40px;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-evenly;
      align-items: center
    }
  }

  .string-section {
    background: #fff;
    border-radius: 8px;
    padding: 24px;

    .string-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: var(--el-text-color-primary);
      }
    }

    .string-input {
      margin-bottom: 20px;

      :deep(.el-textarea__inner) {
        font-size: 14px;
        line-height: 1.6;
      }
    }

    .string-output {
      border: 1px solid var(--el-border-color-light);
      border-radius: 4px;
      overflow: hidden;

      .output-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background-color: var(--el-fill-color-light);
        border-bottom: 1px solid var(--el-border-color-light);

        span {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }

      .output-content {
        :deep(.el-textarea__inner) {
          border: none;
          box-shadow: none;
          background-color: var(--el-fill-color-lighter);
          font-size: 14px;
          line-height: 1.6;
        }
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .upload-container {
    padding: 12px;

    .upload-section,
    .string-section {
      padding: 16px;
    }

    .custom-tabs {
      :deep(.el-tabs__item) {
        padding: 0 12px;
      }
    }
  }
}
</style>